package com.cqc.jdk8.Jutil.concurrent;

import org.junit.Test;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 来源：  https://heuqqdmbyk.feishu.cn/wiki/MUL1wejrviNhsxklCwKcGk01nzh
 * 4.2 如何控制某个方法允许并发访问线程的数量？
 */
public class SemaphoreTest {


    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire();
                    String msg = String.format("time:%s,threadName:%s,threadId:%s,",
                            LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
                            Thread.currentThread().getName(),
                            Thread.currentThread().getId());
                    System.out.println(msg);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                }
            }).start();
        }
    }

}
